package com.mooc.mymooc.controller;

/**
 * 后台相关操作
 */

import com.mooc.mymooc.pojo.*;
import com.mooc.mymooc.service.MoocService;
import com.mooc.mymooc.utils.common.ValidateCode;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
public class BackGroundController {

    @Autowired
    private MoocService moocService;

    @RequestMapping(value = "/background")
    public String backGround() {
        return "background_login";
    }

    @RequestMapping(value = "/makeCode")
    public void makeCode(HttpSession session,HttpServletResponse response) throws Exception {
        ValidateCode validateCode = new ValidateCode();
        String path = session.getServletContext().getRealPath("") + "/code/";
        String endPath = path.replace("\\", "/") + new Date().getTime() + ".png";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        validateCode.write(endPath);
        String code = validateCode.getCode().toString();
        session.setAttribute("code",code);
        File codeFile = new File(endPath);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(codeFile));
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        response.setHeader("Content-Type", "image/png");
        byte b[] = new byte[1024];
        int read;
        try {
            while ((read = bis.read(b)) != -1) {
                bos.write(b, 0, read);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (bis != null) {
                bis.close();
            }
        }

    }

    @RequestMapping(value = "/doBackGroundLogin")
    public void doBackGroundLogin(@RequestBody Admin admin, HttpSession session, HttpServletRequest request,
                                  HttpServletResponse response) throws Exception{
        Admin admin1 = this.moocService.findAdmin(admin);
        JSONObject jsonObject = new JSONObject();
        PrintWriter out = response.getWriter();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        if (admin1!=null){
          jsonObject.put("sta","ok");
          session.setAttribute("admin",admin1);
        }else{
            jsonObject.put("sta","no");
        }
        out.print(jsonObject.toString());
    }

    @RequestMapping("/checkcode")
    public void checkCode(@RequestBody Code code, HttpSession session, HttpServletResponse response,
                          HttpServletRequest request) throws Exception{
        String session_code = (String) session.getAttribute("code");
      String realCode = session_code.toUpperCase();
      String getCode = code.getCode().toUpperCase();
      JSONObject jsonObject = new JSONObject();
      if (realCode.equals(getCode)){
          jsonObject.put("sta","ok");
      }else{
          jsonObject.put("sta","no");
      }
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(jsonObject.toString());
    }

    @RequestMapping(value = "/showIndex")
    public String showIndex(){
        return "main";
    }

    @RequestMapping(value = "/left")
    public String left(){
        return "left";
    }
    @RequestMapping(value = "/top")
    public String top(){
        return "top";
    }
    @RequestMapping(value = "/right")
    public String right(){
        return "right";
    }

    @RequestMapping(value = "/showAddCourseOrg")
    public String showAddCourseOrg(Model model){
        List<City> cityList = this.moocService.findAllCity();
        model.addAttribute("citys",cityList);
        return "addCourseOrg";
    }

    @RequestMapping(value = "/doAddCourseOrg")
    public String doAddCourseOrg(Organization organization, Model model, MultipartFile file,
                                 HttpServletRequest request, Integer city_id){
        String filename = file.getOriginalFilename();
        String path = request.getSession().getServletContext().getRealPath("")+"/courseImg/";
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdirs();
        }
        String newName = UUID.randomUUID()+filename;
        Organization organization1 = new Organization();
        organization1.setName(organization.getName());
        organization1.setDescr(organization.getDescr());
        organization1.setAddress(organization.getAddress());
        organization1.setCt(organization.getCt());
        organization1.setImage("/courseImg/"+newName);
        City city = new City();
        city.setId(city_id);
        organization1.setCity(city);
        Integer rows = this.moocService.addCourseOrg(organization1);
        try {
            file.transferTo(new File(path+File.separator+newName));
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/showAllOrg";
    }

    @RequestMapping(value = "/showAllOrg")
    public String showAllOrg(Organization organization ,Model model,
                             String name,String type){
        if (type!=null){
            organization.setName(name);
        }
        List<Organization> organizationList = this.moocService.findAllOrgUseInBackGround(organization);
        model.addAttribute("orgs",organizationList);
        return "showOrg";
    }

    @RequestMapping(value = "/updateOrg")
    public String updateOrg(Integer flag,Integer id,Model model){
        if (flag==1){
            Organization organization = this.moocService.findOrgById(id);
            List<City> cityList = this.moocService.findAllCity();
            model.addAttribute("org",organization);
            model.addAttribute("citys",cityList);
        }
        return "showUpdateOrg";
    }

    @RequestMapping(value = "/doUpdateOrg")
    public String doUpdateOrg(Organization organization,MultipartFile file,HttpServletRequest request,
                            HttpServletResponse response,Integer city_id,Integer id){
        String url = request.getRequestURI();
        String filename = file.getOriginalFilename();
        String path = request.getSession().getServletContext().getRealPath("")+"/courseImg/";
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdirs();
        }
        String newName = UUID.randomUUID()+filename;
        Organization organization1 = new Organization();
        organization1.setId(id);
        organization1.setName(organization.getName());
        organization1.setDescr(organization.getDescr());
        organization1.setAddress(organization.getAddress());
        organization1.setCt(organization.getCt());
        if (!filename.equals("")) {
            organization1.setImage("/courseImg/" + newName);
        }else{
            organization1.setImage(null);
        }
        City city = new City();
        city.setId(city_id);
        organization1.setCity(city);
        Integer rows = this.moocService.updateOrg(organization1);
        try {
            file.transferTo(new File(path+File.separator+newName));
        }catch (Exception e){
            e.printStackTrace();
        }
        if (rows>0){
           return "redirect:/showAllOrg";
        }else{
            return "redirect:/doUpdateOrg";
        }
    }

    @RequestMapping(value = "/removeOrgs")
    public String removeOrgs(Integer[] ids,Model model){
        for (int i=0;i<ids.length;i++){
            this.moocService.removeOrg(ids[i]);
        }
        return "redirect:/showAllOrg";
    }

    @RequestMapping(value = "/showAddCourse")
    public String showAddCourse(Model model){
        Organization organization = new Organization();
        List<Organization> organizationList = this.moocService.findAllOrgUseInBackGround(organization);
        model.addAttribute("orgs",organizationList);
        return "addCourse";
    }
    @RequestMapping(value = "/getTeacher")
    public void getTeacher(@RequestBody Organization organization,HttpServletResponse response){
        List<Teacher> teacherList = (List<Teacher>) this.moocService.findTeacherByOrg(organization.getId());
        JSONObject jsonObject = new JSONObject();
        Map map = new HashMap();
        map.put("teachers",teacherList);
        jsonObject.put("teacher",map);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        try {
            PrintWriter out = response.getWriter();
            out.print(jsonObject.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @RequestMapping(value = "/doAddCourse")
    public String doAddCourse(Course course, MultipartFile file,Integer teacher_id,
                              HttpServletRequest request,Model model,Integer org_id){
        String filename = file.getOriginalFilename();
        String path = request.getSession().getServletContext().getRealPath("")+"/courseImage/";
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdirs();
        }
        String newFileName = UUID.randomUUID()+filename;
        try {
            file.transferTo(new File(path+File.separator+newFileName));
        }catch (Exception e){
            e.printStackTrace();
        }
        Course dbCourse = new Course();
        dbCourse.setDescr(course.getDescr());
        dbCourse.setImage("/courseImage/"+newFileName);
        dbCourse.setDegree(course.getDegree());
        dbCourse.setDetail(course.getDetail());
        dbCourse.setLearn_time(course.getLearn_time());
        dbCourse.setName(course.getName());
        Teacher teacher = new Teacher();
        teacher.setId(teacher_id);
        dbCourse.setTeacher(teacher);
        Organization organization = new Organization();
        organization.setId(org_id);
        dbCourse.setOrganization(organization);
        Integer rows = this.moocService.addCourse(dbCourse);
        if (rows>0){
            return "redirect:/showAllCourse";
        }else{
            return "redirect:/showAddCourse";
        }
    }
    @RequestMapping(value = "/showAllCourse")
    public String showAllCourse(Course course,Model model,Integer org_id,String type){
        if (type!=null){
            if (org_id!=null && org_id!=0) {
                Organization organization = new Organization();
                organization.setId(org_id);
                course.setOrganization(organization);
            }
            List<Course> courseList = this.moocService.findAllCourseInBackGround(course);
            model.addAttribute("courses",courseList);
            Organization organization = new Organization();
            organization.setId(org_id);
            List<Organization> organizationList = this.moocService.findAllOrgUseInBackGround(organization);
            model.addAttribute("orgs",organizationList);
            return "showCourse";
        }
        List<Course> courseList = this.moocService.findAllCourseInBackGround(course);
        model.addAttribute("courses",courseList);
        Organization organization = new Organization();
        organization.setId(org_id);
        List<Organization> organizationList = this.moocService.findAllOrgUseInBackGround(organization);


         model.addAttribute("orgs",organizationList);
        return "showCourse";
    }

    @RequestMapping(value = "/removeCourse")
    public String removeCourse(Integer[] ids){
        for (int i=0;i<ids.length;i++){
            this.moocService.removeCourse(ids[i]);
        }
        return "redirect:/showAllCourse";
    }
    /*
        执行修改课程操作，flag=1展示原本数据，flag=2提交更改
     */
    @RequestMapping(value = "/updateCourse")
    public String updateCourse(Course courses,String flag,Integer id,Model model,HttpServletRequest request,
                               Integer teacher_id,Integer org_id,MultipartFile file){
        if (flag.equals("1")){
            Course course = this.moocService.findCourseByIdDetail(id);
            Organization organization = course.getOrganization();
            List<Organization> organizationList = this.moocService.findAllOrgUseInBackGround(new Organization());
            List<Teacher> teacherList = (List<Teacher>) this.moocService.findTeacherByOrg(organization.getId());
            Teacher teacher = null;
            Iterator iterator1 = teacherList.iterator();
            while (iterator1.hasNext()){ //解决列表中重复项
                teacher = (Teacher) iterator1.next();
                if (teacher.getId()==course.getTeacher().getId()){
                    iterator1.remove();
                }
            }
            Organization organization1 = null;
            Iterator iterator = organizationList.iterator();
            while (iterator.hasNext()){
                organization1 = (Organization) iterator.next();
                if (organization1.getId()==course.getOrganization().getId()){
                    iterator.remove();
                }
            }
            model.addAttribute("course",course);
            model.addAttribute("orgs",organizationList);
            model.addAttribute("teachers",teacherList);
            return "showUpdateCourse";
        }else{
            Course course = new Course();
            course.setName(courses.getName());
            course.setDetail(courses.getDetail());
            course.setDegree(courses.getDegree());
            course.setLearn_time(courses.getLearn_time());
            course.setDescr(courses.getDescr());
            if (file.getSize()!=0){
                String filename = file.getOriginalFilename();
                String path = request.getSession().getServletContext().getRealPath("")+"/courseImage/";
                File file1 = new File(path);
                if (!file1.exists()){
                    file1.mkdirs();
                }
                String realName = UUID.randomUUID()+filename;
                course.setImage("/courseImage/"+realName);
                try {
                    file.transferTo(new File(path+File.separator+realName));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{
                course.setImage(null);
            }
            Organization organization = new Organization();
            organization.setId(org_id);
            Teacher teacher = new Teacher();
            teacher.setId(teacher_id);
            course.setOrganization(organization);
            course.setTeacher(teacher);
            course.setId(id);
            if (this.moocService.updateCourse(course)>0){
                return "redirect:/showAllCourse";
            }
            return "showUpdateCourse";
        }
    }

    /**
     * 显示添加章节页面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/addLesson")
    public String addLesson(Model model,Integer id){
        List<Course> courseList = this.moocService.findAllCourseInBackGround(new Course());
        if (id!=null) {
            Course course = this.moocService.findCourseByIdDetail(id);
            model.addAttribute("course1",course);
        }
        model.addAttribute("courses",courseList);
        return "addLesson";
    }

    /**
     * 执行添加章节操作
     * @param name
     * @param model
     * @param course_id
     * @return
     */
    @RequestMapping(value = "/doAddLesson")
    public String doAddLesson(String[] name, Model model,Integer course_id){
        Course course = new Course();
        course.setId(course_id);
        for (int i=0;i<name.length;i++){
            Lesson lesson = new Lesson();
            lesson.setName(name[i]);
            lesson.setCourse(course);
            this.moocService.addLesson(lesson);
        }
        return null;
    }

    @RequestMapping(value = "/updateLesson")
    public String updateLesson(Integer id,Model model,String[] name,Integer[] l_id,String flag) {
        if (flag != null && name != null && l_id != null) {
            if (flag.equals("2")) {
                for (int i = 0; i < name.length; i++) {
                    Lesson lesson = new Lesson();
                    lesson.setName(name[i]);
                    lesson.setId(l_id[i]);
                    this.moocService.updateLesson(lesson);
                }
                List<Lesson> lessonList = this.moocService.findLessonById(id);
                Course course = this.moocService.findCourseByIdDetail(id);
                model.addAttribute("lessons", lessonList);
                model.addAttribute("course", course);
                return "showUpdateLesson";
            }
        }
        List<Lesson> lessonList = this.moocService.findLessonById(id);
        Course course = this.moocService.findCourseByIdDetail(id);
        model.addAttribute("lessons", lessonList);
        model.addAttribute("course", course);
        return "showUpdateLesson";
    }

    @RequestMapping("/addVideo")
    public String showAddVideo(Model model){
        List<Course> courseList = this.moocService.findAllCourseInBackGround(new Course());
        model.addAttribute("courses",courseList);
        return "addVideo";
    }

    @RequestMapping(value = "/getLesson")
    public void getLesson(@RequestBody Course course, HttpServletResponse response) throws Exception{
        Integer id = course.getId();
        List<Lesson> lessons = this.moocService.findLessonById(id);
        JSONObject jsonObject = new JSONObject();
        Map map = new HashMap();
        map.put("lessons",lessons);
        if (lessons.size()==0){
            jsonObject.put("msg","当前该课程下没有章节，要想添加视频资源，请先添加章节!");
        }
        jsonObject.put("lesson",map);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter printWriter = response.getWriter();
        printWriter.print(jsonObject.toString());
    }

    /**
     * 上传视频文件
     * @param myfile
     * @param videoname
     * @param request
     * @param response
     * @param lesson_id
     * @param course_id
     * @throws Exception
     */
    @RequestMapping(value = "/uploadVideo")
    public void uploadVideo(MultipartFile myfile,String videoname,HttpServletRequest request,
                            HttpServletResponse response,String lesson_id,String course_id) throws Exception{
        int id = Integer.parseInt(lesson_id);
        int cid = Integer.parseInt(course_id);
        Lesson lesson = this.moocService.findLessonByIdInBackGround(id);
        Course course = this.moocService.findCourseByIdDetail(cid);
        String filename = myfile.getOriginalFilename();
        String path = request.getSession().getServletContext().getRealPath("")+"/video/"+course.getName()+"/"+lesson.getName()+"/";
        int at = filename.indexOf('.');
        String ext = filename.substring(at+1,filename.length());
        String saveName = videoname+"."+ext;
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        myfile.transferTo(new File(path+File.separator+saveName));
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter printWriter = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("infos","success");
        printWriter.print(jsonObject.toString());
    }

    /**
     * 添加视频信息到数据库
     * @param lesson_id
     * @param course_id
     * @param name
     * @param file
     * @return
     */
    @RequestMapping(value = "/doAddVideo")
    public String doAddVideo(Integer lesson_id,Integer course_id,String[] name,MultipartFile[] file){
        Lesson lesson = new Lesson();
        lesson.setId(lesson_id);
        for (int k=0;k<name.length;k++){
            Integer index = file[k].getOriginalFilename().indexOf('.');
            String ext = file[k].getOriginalFilename().substring(index+1,file[k].getOriginalFilename().length());
            String realName = name[k]+"."+ext;
            CourseVideo video = new CourseVideo();
            video.setLesson(lesson);
            video.setName(name[k]);
            video.setVideo_name(realName);
            this.moocService.addVideo(video);
        }
        return null;
    }

    /**
     * 显示所有留言或根据条件查找筛选留言
     * @param model
     * @param request
     * @param type
     * @param course_id
     * @param name
     * @return
     */
    @RequestMapping("/showAllComments")
    public String showAllComments(Model model,HttpServletRequest request,String type,Integer course_id,String name){
        CourseComments courseComments = new CourseComments();
        if (type!=null){
            Course course = new Course();
            if (course_id!=null && course_id!=0){
                course.setId(course_id);
                courseComments.setCourse(course);
            }
            if (name!=null && name!=""){
                courseComments.setComments(name);
            }
        }
        List<CourseComments> courseCommentsList = this.moocService.findAllComment(courseComments);
        List<Course> courseList = this.moocService.findAllCourseInBackGround(new Course());
        model.addAttribute("comments",courseCommentsList);
        model.addAttribute("courses",courseList);
        return "showComment";
    }

    /**
     * 删除留言
     */
    @RequestMapping(value = "/deleteComments")
    public String deleteComments(Integer[] ids){
        for (int i=0;i<ids.length;i++){
            this.moocService.deleteComments(ids[i]);
        }
        return "redirect:/showAllComments";
    }

    /**
     * 向所有用户发送站内消息
     */
    @RequestMapping(value = "/sendMessage")
    public String sendMessage(String type,Model model,String message){
        if (type==""|| type==null) {
            return "addMessage";
        }
      List<User> users = this.moocService.findAllUser();
      Iterator iterator = users.iterator();
      User user = null;
      UserMessage userMessage = new UserMessage();
      userMessage.setMessage(message);
      userMessage.setHas_read(1);
      while (iterator.hasNext()){
        user = (User) iterator.next();
        userMessage.setUser(user);
        this.moocService.sendMessageToUser(userMessage);
      }
      return "addMessage";
    }

    /**
     * 增加教师 显示增加教师界面，完成教师添加逻辑
     * @param teacher
     * @param org_id
     * @param type
     * @param model
     * @return
     */
    @RequestMapping(value = "/addTeacher")
    public String addTeacher(Teacher teacher, Integer org_id,String type,Model model){
        List<Organization> organizationList = this.moocService.findAllOrgUseInBackGround(new Organization());
        if (type==null){
            model.addAttribute("orgs",organizationList);
            return "addTeacher";
        }
        Organization organization = this.moocService.findOrgById(org_id);
        teacher.setOrganization(organization);
        model.addAttribute("orgs",organizationList);
        if (this.moocService.addTeacher(teacher)>0){
            return "redirect:/showAllTeacher";
        }
        return "addTeacher";

    }

    /**
     * 显示所有教师信息
     * @param model
     * @param type
     * @param name
     * @return
     */
    @RequestMapping(value = "/showAllTeacher")
    public String showAllTeacher(Model model,String type,String name){
        Teacher teacher = new Teacher();
        if (type!=null) {
            if (name != null) {
                teacher.setName(name);
            }
        }
        List<Teacher> teacherList = this.moocService.findTeacherInBackGround(teacher);
        model.addAttribute("teachers",teacherList);
        return "showTeacher";
    }

    /**
     * 删除教师
     * @param ids
     * @return
     */
    @RequestMapping(value = "/removeTeachers")
    public String removeTeachers(Integer[] ids){
        for (int i=0;i<ids.length;i++){
            this.moocService.removeTeacher(ids[i]);
        }
        return "redirect:/showAllTeacher";
    }

    @RequestMapping("/updateTeacher")
    public String updateTeacher(Teacher teacher,Integer id,
                                Model model,String type,Integer org_id){
       if (type==null){
           List<Organization> organizationList = this.moocService.findAllOrgUseInBackGround(new Organization());
           Teacher teacher1 = this.moocService.findTeacherById(id);
           Organization organization = teacher1.getOrganization();
           Organization organization1 = null;
           Iterator iterator = organizationList.iterator();
           while (iterator.hasNext()){
               organization1 = (Organization) iterator.next();
               if (organization1.getId()==organization.getId()){
                   iterator.remove();
               }
           }
           model.addAttribute("orgs",organizationList);
           model.addAttribute("teacher",teacher1);
           return "showUpdateTeacher";
       }
       Organization organization = this.moocService.findOrgById(org_id);
       teacher.setId(id);
       teacher.setOrganization(organization);
       Integer rows = this.moocService.updateTeacher(teacher);
       if (rows>0){
           return "redirect:/showAllTeacher";
       }else{
           return "showUpdateTeacher";
       }
    }

    @RequestMapping(value = "/addTurnPage")
    public String addTurnPage(MultipartFile[] file,String type,HttpSession session,
                              String[] title,String[] url){
        if (type==null){
            return "addTurnPage";
        }
        String path = session.getServletContext().getRealPath("")+"/turnPage/";
        Banner banner = new Banner();
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdirs();
        }
        for (int i=0;i<file.length;i++) {
            if (file[i].getSize() != 0) {
                String filename = file[i].getOriginalFilename();
                String newName = "tp" + new Date().getTime() + ".jpg";
                banner.setImage("/turnPage/" + newName);
                banner.setIndex(i);
                banner.setTitle(title[i]);
                banner.setUrl(url[i]);
                try {
                    file[i].transferTo(new File(path + File.separator + newName));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Integer rows=0;
                try {
                    rows = this.moocService.updateBanner(banner);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
                if (rows==0) {
                    this.moocService.addBanner(banner);
                }
            }
        }
        return null;
    }
}
